<template>
  <div class="app-container">
    <el-card>
      <!-- 搜索表单 -->
      <el-form :model="queryParams" ref="queryFormRef" :inline="true" class="search-form">
        <el-form-item label="字典名称" prop="name">
          <el-input v-model="queryParams.name" placeholder="请输入字典名称" clearable style="width: 240px" @keyup.enter="handleQuery" />
        </el-form-item>
        <el-form-item label="字典类型" prop="type">
          <el-input v-model="queryParams.type" placeholder="请输入字典类型" clearable style="width: 240px" @keyup.enter="handleQuery" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="queryParams.status" placeholder="字典状态" clearable style="width: 240px">
            <el-option v-for="dict in statusOptions" :key="dict.value" :label="dict.label" :value="dict.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="创建时间">
          <el-date-picker
            v-model="dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            style="width: 240px"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" :icon="Search" @click="handleQuery">搜索</el-button>
          <el-button :icon="Refresh" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>

      <!-- 操作按钮 -->
      <el-row :gutter="10" class="mb-3">
        <el-col :span="1.5">
          <el-button type="primary" :icon="Plus" @click="handleAdd">新增</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button type="warning" :icon="RefreshLeft" @click="handleRefreshCache">刷新缓存</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button type="danger" :icon="Delete" :disabled="selectedIds.length === 0" @click="handleBatchDelete">批量删除</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button type="success" :icon="Download" @click="handleExport">导出</el-button>
        </el-col>
      </el-row>

      <!-- 表格 -->
      <el-table 
        v-loading="loading" 
        :data="typeList" 
        @selection-change="handleSelectionChange"
        @row-click="handleRowClick"
        row-key="id"
      >
        <el-table-column type="selection" width="50" align="center" />
        <el-table-column label="字典编号" prop="id" width="80" />
        <el-table-column label="字典名称" prop="name" :show-overflow-tooltip="true" />
        <el-table-column label="字典类型" prop="type" :show-overflow-tooltip="true" />
        <el-table-column prop="status" label="状态" align="center" width="100">
          <template #default="scope">
            <dict-tag dict-type="sys_normal_disable" :value="scope.row.status" />
          </template>
        </el-table-column>
        <el-table-column label="备注" prop="description" :show-overflow-tooltip="true" />
        <el-table-column label="创建时间" align="center" prop="createdAt" width="160">
          <template #default="scope">
            <span>{{ formatDateTime(scope.row.createdAt) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="260" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-button type="primary" link :icon="View" @click.stop="handleDict(scope.row)">数据</el-button>
            <el-button type="primary" link :icon="Edit" @click.stop="handleUpdate(scope.row)">修改</el-button>
            <el-button type="danger" link :icon="Delete" @click.stop="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <pagination
        v-if="total > 0"
        :total="total"
        v-model:page="queryParams.page"
        v-model:limit="queryParams.limit"
        @pagination="getList"
      />
    </el-card>

    <!-- 添加/修改对话框 -->
    <el-dialog :title="dialog.title" v-model="dialog.visible" width="600px" append-to-body>
      <el-form ref="typeFormRef" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="字典名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入字典名称" />
        </el-form-item>
        <el-form-item label="字典类型" prop="type">
          <el-input v-model="form.type" placeholder="请输入字典类型" :disabled="form.id !== undefined" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <dict-radio
            v-model="form.status"
            dict-type="sys_normal_disable"
          />
        </el-form-item>
        <el-form-item label="备注" prop="description">
          <el-input v-model="form.description" type="textarea" placeholder="请输入备注" :rows="3" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="dialog.visible = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { Search, Refresh, Plus, Delete, View, Edit, Download, RefreshLeft } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useRouter } from 'vue-router'
import {
  getDictTypeList,
  getDictTypeDetail,
  createDictType,
  updateDictType,
  deleteDictType,
  refreshDictCache,
  exportDictType
} from '@/api/dict'
import Pagination from '@/components/Pagination/index.vue'
import useDict from '@/hooks/useDict'

const router = useRouter()

// 状态数据字典
const statusOptions = [
  { value: 1, label: '正常' },
  { value: 0, label: '禁用' }
]

// 查询参数
const queryParams = reactive({
  page: 1,
  limit: 10,
  name: '',
  type: '',
  status: undefined
})

// 日期范围
const dateRange = ref([])

// 表格数据
const typeList = ref([])
const loading = ref(false)
const total = ref(0)
const selectedIds = ref([])
const queryFormRef = ref(null)
const typeFormRef = ref(null)

// 表单参数
const form = reactive({
  name: '',
  type: '',
  status: 1,
  description: ''
})

// 表单验证规则
const rules = {
  name: [
    { required: true, message: '字典名称不能为空', trigger: 'blur' }
  ],
  type: [
    { required: true, message: '字典类型不能为空', trigger: 'blur' },
    { pattern: /^[a-z0-9_]+$/, message: '字典类型只能由小写字母、数字、下划线组成', trigger: 'blur' }
  ]
}

// 弹窗对象
const dialog = reactive({
  title: '',
  visible: false
})

// 字典数据
const { dicts } = useDict('sys_normal_disable')

// 格式化日期时间
const formatDateTime = (value) => {
  if (!value) return ''
  return new Date(value).toLocaleString()
}

// 获取字典类型列表
const getList = async () => {
  loading.value = true
  try {
    // 处理日期范围
    const params = { ...queryParams }
    if (dateRange.value && dateRange.value.length === 2) {
      params.beginTime = dateRange.value[0]
      params.endTime = dateRange.value[1]
    }
    
    const res = await getDictTypeList(params)
    typeList.value = res.data.list
    total.value = res.data.total
  } catch (error) {
    console.error('获取字典类型列表失败:', error)
  } finally {
    loading.value = false
  }
}

// 搜索按钮操作
const handleQuery = () => {
  queryParams.page = 1
  getList()
}

// 重置按钮操作
const resetQuery = () => {
  dateRange.value = []
  queryFormRef.value.resetFields()
  handleQuery()
}

// 多选框选中数据
const handleSelectionChange = (selection) => {
  selectedIds.value = selection.map(item => item.id)
}

// 行点击事件
const handleRowClick = (row) => {
  // 避免与按钮操作冲突，这里不做任何处理
}

// 新增按钮操作
const handleAdd = () => {
  resetForm()
  dialog.title = '添加字典类型'
  dialog.visible = true
}

// 修改按钮操作
const handleUpdate = async (row) => {
  resetForm()
  dialog.title = '修改字典类型'
  dialog.visible = true
  loading.value = true
  
  try {
    const res = await getDictTypeDetail(row.id)
    Object.assign(form, res.data)
  } catch (error) {
    console.error('获取字典类型详情失败:', error)
  } finally {
    loading.value = false
  }
}

// 查看字典数据
const handleDict = (row) => {
  router.push({
    path: '/system/dict/data',
    query: { dictType: row.type }
  })
}

// 表单重置
const resetForm = () => {
  typeFormRef.value?.resetFields()
  Object.assign(form, {
    name: '',
    type: '',
    status: 1,
    description: ''
  })
}

// 删除按钮操作
const handleDelete = (row) => {
  ElMessageBox.confirm(`确认删除字典类型"${row.name}"吗?`, '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      await deleteDictType(row.id)
      ElMessage.success('删除成功')
      getList()
    } catch (error) {
      console.error('删除失败:', error)
      ElMessage.error('删除失败')
    }
  })
}

// 批量删除操作
const handleBatchDelete = () => {
  if (selectedIds.value.length === 0) {
    ElMessage.warning('请至少选择一条记录')
    return
  }
  
  const dictNames = typeList.value
    .filter(item => selectedIds.value.includes(item.id))
    .map(item => item.name)
    .join('、')
  
  ElMessageBox.confirm(`确认删除选中的${selectedIds.value.length}条字典类型(${dictNames})吗?`, '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      await Promise.all(selectedIds.value.map(id => deleteDictType(id)))
      ElMessage.success('批量删除成功')
      getList()
    } catch (error) {
      console.error('批量删除失败:', error)
      ElMessage.error('批量删除失败')
    }
  })
}

// 提交表单
const submitForm = () => {
  typeFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        loading.value = true
        if (form.id) {
          await updateDictType(form.id, form)
          ElMessage.success('修改成功')
        } else {
          await createDictType(form)
          ElMessage.success('添加成功')
        }
        dialog.visible = false
        getList()
      } catch (error) {
        console.error('提交失败:', error)
        ElMessage.error('提交失败')
      } finally {
        loading.value = false
      }
    }
  })
}

// 刷新缓存
const handleRefreshCache = async () => {
  try {
    await refreshDictCache()
    ElMessage.success('刷新缓存成功')
  } catch (error) {
    console.error('刷新缓存失败:', error)
    ElMessage.error('刷新缓存失败')
  }
}

// 导出字典类型
const handleExport = async () => {
  try {
    // 处理日期范围
    const params = { ...queryParams }
    delete params.page
    delete params.limit
    
    if (dateRange.value && dateRange.value.length === 2) {
      params.beginTime = dateRange.value[0]
      params.endTime = dateRange.value[1]
    }
    
    const res = await exportDictType(params)
    const blob = new Blob([res.data], { type: 'application/vnd.ms-excel' })
    const link = document.createElement('a')
    link.href = URL.createObjectURL(blob)
    link.download = '字典类型.xlsx'
    link.click()
    URL.revokeObjectURL(link.href)
  } catch (error) {
    console.error('导出失败:', error)
    ElMessage.error('导出失败')
  }
}

onMounted(() => {
  getList()
})
</script>

<style lang="scss" scoped>
.app-container {
  padding: 20px;
}

.search-form {
  margin-bottom: 20px;
}

.mb-3 {
  margin-bottom: 10px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
}
</style> 